package com.iplant.aps.serviceimpl.dao;

import com.iplant.aps.service.mesenum.MESDBSource;
import com.iplant.aps.service.po.OutResult;
import com.iplant.aps.service.po.ServiceResult;
import com.iplant.aps.service.po.bms.BMSEmployee;
import com.iplant.aps.service.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 数据库访问业务基础类
 *
 * @author YouWang·Peng
 * 2021-6-10 10:17:32
 */
public class APSBaseDAO extends BaseDAO {
    private static Logger logger = LoggerFactory.getLogger(APSBaseDAO.class);

    private static APSBaseDAO Instance = null;

    private APSBaseDAO() {
        super();
    }

    public static APSBaseDAO getInstance() {
        if (Instance == null)
            Instance = new APSBaseDAO();
        return Instance;
    }

    /**
     * 获取最新的编码
     */
    public String GetNewCode(BMSEmployee wLoginUser, String wTableName, OutResult<Integer> wErrorCode) {
        String wResult = "";
        try {
            ServiceResult<String> wInstance = this.GetDataBaseName(wLoginUser, MESDBSource.Basic, 0);
            wErrorCode.set(wInstance.ErrorCode);
            if (wErrorCode.Result != 0) {
                return wResult;
            }

            String wSQL = StringUtils.Format(
                    "SELECT Code FROM {0}.{1} WHERE id IN( SELECT MAX(ID) FROM {0}.{1});",
                    wInstance.Result, wTableName);

            Map<String, Object> wParamMap = new HashMap<>();

            wSQL = this.DMLChange(wSQL);

            List<Map<String, Object>> wQueryResult = shrisJdbcTemplate.queryForList(wSQL, wParamMap);

            int wNumber = 1;
            int wMonth = Calendar.getInstance().get(Calendar.MONTH) + 1;
            for (Map<String, Object> wReader : wQueryResult) {
                String wDemandNo = StringUtils.parseString(wReader.get("Code"));
                int wCodeMonth = StringUtils.parseInt(wDemandNo.substring(7, 9));
                if (wMonth > wCodeMonth)
                    wNumber = 1;
                else
                    wNumber = StringUtils.parseInt(wDemandNo.substring(10)) + 1;
            }

            //TLD2022020009
            wResult = StringUtils.Format("TLD{0}{1}{2}", String.valueOf(Calendar.getInstance().get(Calendar.YEAR)),
                    String.format("%02d", Calendar.getInstance().get(Calendar.MONTH) + 1),
                    String.format("%04d", wNumber));
        } catch (Exception ex) {
            logger.error(ex.toString());
        }
        return wResult;
    }
}
